from sys import argv
from subprocess import run

def get_output(cmd):
    """
    Return output as running the command in terminal.
    """
    output = run(cmd, shell=True, capture_output=True, text=True)
    return output.stdout[:-1]

def run_cmd(cmd):
    """
    Running the specific command.
    """
    run(cmd, shell=True)

def decompile(source:str, target:str):
    """
    Decompile from source, output the result to target.
    """
    run_cmd('javap {} > {}.java'.format(source, target))



def main():
    argc = len(argv)
    if argc > 1:
        source_dir = argv[1]
    if argc > 2:
        target_dir = argv[2]

    files = get_output('ls {}'.format(source_dir)).split()
    raw_files = [single for single in files if '.class' in single]

    print('decompile:')

    for single in raw_files:
        new_name = single.rstrip('.class')
        decompile(source_dir + single, target_dir + new_name)
        print('+', new_name + '.java')

    print('Successful:', len(raw_files))


if __name__ == '__main__':
    main()